import React, { useRef, useState, useEffect, useCallback } from 'react';
import './ImageViewer.css';

const SimpleImageViewer = ({ 
  data, 
  type, 
  viewId, 
  currentTool, 
  title, 
  enableInterpolation = true,
  // TDC相关props
  showTdcButton = false,
  tdcMode = false,
  onToggleTdc,
  // 血管提取相关props
  showVesselButton = false,
  vesselMode = false,
  onToggleVessel,
  // 动脉输入点相关props
  processingMethod = 'normal',
  arterialInputPoint = null,
  onArterialInputPointChange
}) => {
  const canvasRef = useRef(null);
  const containerRef = useRef(null);
  const imageRef = useRef(null); // 缓存加载的图像
  const [viewport, setViewport] = useState({
    scale: 1,
    translation: { x: 0, y: 0 },
    windowWidth: 256,
    windowCenter: 128
  });
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [lastMousePos, setLastMousePos] = useState({ x: 0, y: 0 });
  const [imageLoaded, setImageLoaded] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
  
  // 灰度值拾取相关状态
  const [pixelInfo, setPixelInfo] = useState(null); // 存储当前像素信息
  const [showPixelInfo, setShowPixelInfo] = useState(false); // 控制像素信息显示

  // 获取容器尺寸 - 使用更直接的方式
  const updateContainerSize = () => {
    if (containerRef.current) {
      const rect = containerRef.current.getBoundingClientRect();
      const newWidth = Math.floor(rect.width);
      const newHeight = Math.floor(rect.height);
      
      console.log('Container rect:', newWidth, newHeight);
      
      // 直接设置尺寸，不做比较
      setContainerSize({ width: newWidth, height: newHeight });
    }
  };

  // 简化的容器大小监听
  useEffect(() => {
    // 立即获取一次尺寸
    updateContainerSize();
    
    // 监听窗口大小变化
    const handleResize = () => {
      updateContainerSize();
    };
    
    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  // 当data变化时，重新获取容器尺寸
  useEffect(() => {
    if (data) {
      // 延迟一帧确保DOM更新完成
      requestAnimationFrame(() => {
        updateContainerSize();
      });
    }
  }, [data]);

  // 当容器大小变化时重新绘制
  useEffect(() => {
    if (imageRef.current && imageLoaded && containerSize.width > 0 && containerSize.height > 0) {
      drawImage();
    }
  }, [containerSize, imageLoaded]);

  // 处理初始缩放 - 确保图像和容器都准备好后计算最合适的缩放
  useEffect(() => {
    if (imageRef.current && imageLoaded && containerSize.width > 0 && containerSize.height > 0) {
      // 检查当前缩放是否是默认值，如果是则计算合适的初始缩放
      if (viewport.scale === 1) {
        console.log('Calculating initial fit scale...');
        const initialScale = calculateFitScale(imageRef.current);
        if (initialScale !== 1) {
          updateViewportSafely({
            scale: initialScale,
            translation: { x: 0, y: 0 },
            ...(type === 'processed' && {
              windowWidth: 255,
              windowCenter: 127.5
            })
          });
        }
      }
    }
  }, [imageLoaded, containerSize, type]);

  useEffect(() => {
    if (data) {
      console.log('SimpleImageViewer received data:', type, data);
      loadImageData();
    }
  }, [data, currentImageIndex]);

  // 只在viewport变化或插值设置变化时重绘（去抖动）
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      if (imageRef.current && imageLoaded) {
        drawImage();
      }
    }, 16); // 约60fps的防抖

    return () => clearTimeout(timeoutId);
  }, [viewport, imageLoaded, enableInterpolation]);

  // 监听动脉输入点变化，触发重新绘制
  useEffect(() => {
    console.log('动脉输入点状态变化，重新绘制:', arterialInputPoint);
    if (imageRef.current && imageLoaded) {
      drawImage();
    }
  }, [arterialInputPoint, imageLoaded]);

  // 设置Canvas上下文的图像平滑选项
  const configureCanvasSmoothing = (ctx) => {
    if (ctx) {
      ctx.imageSmoothingEnabled = enableInterpolation;
      if (enableInterpolation) {
        // 当启用插值时，使用高质量设置
        ctx.imageSmoothingQuality = 'high';
      }
    }
  };

  // 分离图像加载和绘制逻辑
  const loadImageData = async () => {
    setImageLoaded(false);
    setErrorMessage('');

    try {
      if (type === 'dicom' && data.images && data.images.length > 0) {
        // 显示DICOM图像
        const imageData = data.images[currentImageIndex];
        console.log('Loading DICOM image:', currentImageIndex, imageData);
        
        if (imageData && imageData.imageId) {
          const img = new Image();
          img.crossOrigin = 'anonymous';
          
          img.onload = () => {
            console.log('Image loaded successfully:', img.width, img.height);
            imageRef.current = img;
            setImageLoaded(true);
            // 不在这里计算初始缩放，等容器尺寸准备好后统一处理
          };
          
          img.onerror = (error) => {
            console.error('Image load failed:', error);
            setErrorMessage('图像加载失败');
          };
          
          img.src = imageData.imageId;
        } else {
          setErrorMessage('无效的图像数据');
        }
      } else if (type === 'processed' && data) {
        // 显示处理后的参数图像 - 创建灰度图像而不是伪彩色图像
        console.log('Creating grayscale image for processing:', data);
        const grayscaleImageUrl = createGrayscaleImage(data);
        
        const img = new Image();
        img.onload = () => {
          console.log('Grayscale parameter image loaded successfully');
          imageRef.current = img;
          setImageLoaded(true);
          // 不在这里计算初始缩放，等容器尺寸准备好后统一处理
        };
        
        img.onerror = (error) => {
          console.error('Grayscale parameter image load failed:', error);
          setErrorMessage('参数图像生成失败');
        };
        
        img.src = grayscaleImageUrl;
      }
    } catch (error) {
      console.error('加载图像失败:', error);
      setErrorMessage('加载失败: ' + error.message);
    }
  };

  // 计算适应容器的缩放比例
  const calculateFitScale = (img) => {
    if (!img) return 1;
    
    // 如果容器尺寸还没有获取到，返回默认缩放
    if (containerSize.width === 0 || containerSize.height === 0) {
      console.log('Container size not ready for fit calculation');
      return 1;
    }
    
    const imageAspect = img.width / img.height;
    const containerAspect = containerSize.width / containerSize.height;
    
    let scale;
    if (imageAspect > containerAspect) {
      // 图像更宽，按宽度适应
      scale = (containerSize.width * 0.95) / img.width;
    } else {
      // 图像更高，按高度适应
      scale = (containerSize.height * 0.95) / img.height;
    }
    
    const finalScale = Math.max(0.1, Math.min(10, scale));
    console.log(`Fit scale calculated: ${finalScale.toFixed(3)}x (image: ${img.width}×${img.height}, container: ${containerSize.width}×${containerSize.height})`);
    return finalScale;
  };

  // 安全的viewport更新函数
  const updateViewportSafely = (updates) => {
    setViewport(prev => {
      const newViewport = { ...prev, ...updates };
      // 检查是否真的需要更新
      const isChanged = Object.keys(updates).some(key => prev[key] !== newViewport[key]);
      return isChanged ? newViewport : prev;
    });
  };

  const drawImage = () => {
    const canvas = canvasRef.current;
    const img = imageRef.current;
    if (!canvas || !img) return;

    console.log('SimpleImageViewer.drawImage called:', { 
      type, 
      hasData: !!data, 
      currentImageIndex, 
      enableInterpolation 
    });
    
    // 设置canvas尺寸为容器大小
    canvas.width = containerSize.width;
    canvas.height = containerSize.height;
    
    const ctx = canvas.getContext('2d');
    
    // 配置图像平滑
    configureCanvasSmoothing(ctx);
    
    // 清空画布
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    try {
      if (type === 'dicom') {
        // 对DICOM图像应用窗宽窗位调整
        drawImageWithWindowLevel(ctx, img);
      } else if (type === 'processed') {
        // 对处理后的参数图像应用窗宽窗位调整 + 伪彩色映射
        drawProcessedImageWithPseudoColor(ctx, img);
      } else {
        // 其他图像直接绘制
        drawImageWithViewport(ctx, img);
      }
    } catch (error) {
      console.error('绘制图像失败:', error);
      setErrorMessage('绘制失败: ' + error.message);
    }
  };

  const drawImageWithViewport = (ctx, img) => {
    const canvas = canvasRef.current;
    if (!canvas || !img) return;

    try {
      ctx.save();
      
      // 配置图像平滑
      configureCanvasSmoothing(ctx);
      
      // 应用变换
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.scale(viewport.scale, viewport.scale);
      ctx.translate(viewport.translation.x, viewport.translation.y);
      
      // 绘制图像 - 居中显示
      const drawWidth = img.width;
      const drawHeight = img.height;
      ctx.drawImage(img, -drawWidth / 2, -drawHeight / 2, drawWidth, drawHeight);
      
      ctx.restore();
      
      // 绘制动脉输入点标记
      drawArterialInputPoint(ctx, img);
      
      console.log('Image drawn successfully:', drawWidth, drawHeight, viewport.scale);
    } catch (error) {
      console.error('Error drawing image with viewport:', error);
    }
  };

  // 绘制动脉输入点标记
  const drawArterialInputPoint = (ctx, img) => {
    console.log('drawArterialInputPoint 开始执行');
    console.log('arterialInputPoint:', arterialInputPoint);
    console.log('img:', !!img);
    
    if (!arterialInputPoint || !img) {
      console.log('动脉输入点或图像为空，不绘制');
      return;
    }

    const canvas = canvasRef.current;
    if (!canvas) {
      console.log('canvas 为空，不绘制');
      return;
    }

    try {
      const { x, y } = arterialInputPoint;
      const { scale, translation } = viewport;

      console.log('绘制参数:', { x, y, scale, translation });

      // 计算动脉输入点在canvas上的位置
      const displayWidth = img.width * scale;
      const displayHeight = img.height * scale;
      const displayX = (canvas.width - displayWidth) / 2 + translation.x;
      const displayY = (canvas.height - displayHeight) / 2 + translation.y;

      const pointX = displayX + (x / img.width) * displayWidth;
      const pointY = displayY + (y / img.height) * displayHeight;

      console.log('动脉输入点在canvas上的位置:', { pointX, pointY });

      // 绘制动脉输入点标记
      ctx.save();
      
      // 绘制十字线标记
      ctx.strokeStyle = '#ff0000'; // 红色
      ctx.lineWidth = 2;
      ctx.setLineDash([]); // 实线
      
      const crossSize = 10;
      
      // 水平线
      ctx.beginPath();
      ctx.moveTo(pointX - crossSize, pointY);
      ctx.lineTo(pointX + crossSize, pointY);
      ctx.stroke();
      
      // 垂直线
      ctx.beginPath();
      ctx.moveTo(pointX, pointY - crossSize);
      ctx.lineTo(pointX, pointY + crossSize);
      ctx.stroke();
      
      // 绘制中心圆点
      ctx.fillStyle = '#ff0000';
      ctx.beginPath();
      ctx.arc(pointX, pointY, 3, 0, 2 * Math.PI);
      ctx.fill();
      
      // 绘制标签
      ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
      ctx.fillRect(pointX + 15, pointY - 12, 80, 16);
      ctx.fillStyle = '#ffffff';
      ctx.font = '12px -apple-system, BlinkMacSystemFont, sans-serif';
      ctx.fillText('动脉输入点', pointX + 18, pointY - 2);
      
      ctx.restore();
      
      console.log('动脉输入点绘制完成');
      
    } catch (error) {
      console.error('Error drawing arterial input point:', error);
    }
  };

  const drawImageWithWindowLevel = (ctx, img) => {
    const canvas = canvasRef.current;
    if (!canvas || !img) return;

    try {
      // 创建临时canvas来处理窗宽窗位
      const tempCanvas = document.createElement('canvas');
      const tempCtx = tempCanvas.getContext('2d');
      tempCanvas.width = img.width;
      tempCanvas.height = img.height;
      
      // 配置临时canvas的图像平滑
      configureCanvasSmoothing(tempCtx);
      
      // 绘制原始图像到临时canvas
      tempCtx.drawImage(img, 0, 0);
      
      // 获取图像数据
      const imageData = tempCtx.getImageData(0, 0, img.width, img.height);
      const data = imageData.data;
      
      // 应用窗宽窗位调整
      const { windowWidth, windowCenter } = viewport;
      const windowMin = windowCenter - windowWidth / 2;
      const windowMax = windowCenter + windowWidth / 2;
      
      for (let i = 0; i < data.length; i += 4) {
        // 获取灰度值（假设是灰度图像，R=G=B）
        let grayValue = data[i]; // Red channel
        
        // 应用窗宽窗位
        if (grayValue <= windowMin) {
          grayValue = 0;
        } else if (grayValue >= windowMax) {
          grayValue = 255;
        } else {
          grayValue = Math.round(((grayValue - windowMin) / windowWidth) * 255);
        }
        
        // 设置RGB值
        data[i] = grayValue;     // Red
        data[i + 1] = grayValue; // Green
        data[i + 2] = grayValue; // Blue
        // Alpha保持不变
      }
      
      // 将处理后的数据写回临时canvas
      tempCtx.putImageData(imageData, 0, 0);
      
      // 应用视口变换并绘制到主canvas
      ctx.save();
      
      // 配置主canvas的图像平滑
      configureCanvasSmoothing(ctx);
      
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.scale(viewport.scale, viewport.scale);
      ctx.translate(viewport.translation.x, viewport.translation.y);
      
      ctx.drawImage(tempCanvas, -img.width / 2, -img.height / 2);
      
      ctx.restore();
      
      // 绘制动脉输入点标记
      drawArterialInputPoint(ctx, img);
      
      console.log('Image drawn with window/level:', windowCenter, windowWidth);
    } catch (error) {
      console.error('Error drawing image with window/level:', error);
      // 降级到普通绘制
      drawImageWithViewport(ctx, img);
    }
  };

  // 新增：创建灰度图像而不是伪彩色图像
  const createGrayscaleImage = (processedData) => {
    try {
      const canvas = document.createElement('canvas');
      const width = processedData.width || 256;
      const height = processedData.height || 256;
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext('2d');
      
      const imageData = ctx.createImageData(width, height);
      const pixelData = imageData.data;
      
      // 检查数据有效性
      if (!processedData.data || 
          (!Array.isArray(processedData.data) && 
           !(processedData.data instanceof Float32Array) && 
           !(processedData.data instanceof Float64Array) && 
           !(processedData.data instanceof Int32Array) && 
           !(processedData.data instanceof Uint32Array) && 
           !(processedData.data instanceof Int16Array) && 
           !(processedData.data instanceof Uint16Array) && 
           !(processedData.data instanceof Int8Array) && 
           !(processedData.data instanceof Uint8Array) && 
           typeof processedData.data[Symbol.iterator] !== 'function')) {
        console.error('Invalid processed data:', processedData);
        throw new Error('Invalid processed data');
      }
      
      // 直接将原始数据转换为8位灰度图像
      const originalData = processedData.data;
      
      // 找到数据范围，使用循环避免栈溢出
      let min = Infinity;
      let max = -Infinity;
      for (let i = 0; i < originalData.length; i++) {
        const value = originalData[i];
        if (!isNaN(value) && isFinite(value)) {
          if (value < min) min = value;
          if (value > max) max = value;
        }
      }
      
      const range = max - min;
      console.log('Parameter data range:', min, max);
      
      // 转换为8位灰度值
      for (let i = 0; i < originalData.length && i < width * height; i++) {
        let grayValue;
        if (range === 0) {
          grayValue = 128; // 中间灰度
        } else {
          grayValue = Math.round(((originalData[i] - min) / range) * 255);
        }
        
        pixelData[i * 4] = grayValue;     // Red
        pixelData[i * 4 + 1] = grayValue; // Green
        pixelData[i * 4 + 2] = grayValue; // Blue
        pixelData[i * 4 + 3] = 255;       // Alpha
      }
      
      ctx.putImageData(imageData, 0, 0);
      console.log('Grayscale parameter image created:', width, height);
      return canvas.toDataURL();
    } catch (error) {
      console.error('Error creating grayscale image:', error);
      throw error;
    }
  };

  // 新增：绘制处理后的图像，支持窗宽窗位和伪彩色映射
  const drawProcessedImageWithPseudoColor = (ctx, img) => {
    const canvas = canvasRef.current;
    if (!canvas || !img) return;

    try {
      // 创建临时canvas来处理窗宽窗位和伪彩色映射
      const tempCanvas = document.createElement('canvas');
      const tempCtx = tempCanvas.getContext('2d');
      tempCanvas.width = img.width;
      tempCanvas.height = img.height;
      
      // 配置临时canvas的图像平滑
      configureCanvasSmoothing(tempCtx);
      
      // 绘制原始灰度图像到临时canvas
      tempCtx.drawImage(img, 0, 0);
      
      // 获取图像数据
      const imageData = tempCtx.getImageData(0, 0, img.width, img.height);
      const pixelData = imageData.data;
      
      // 应用窗宽窗位调整和伪彩色映射
      const { windowWidth, windowCenter } = viewport;
      const windowMin = windowCenter - windowWidth / 2;
      const windowMax = windowCenter + windowWidth / 2;
      
      for (let i = 0; i < pixelData.length; i += 4) {
        // 获取灰度值
        let grayValue = pixelData[i]; // Red channel (应该与Green、Blue相同)
        
        // 应用窗宽窗位归一化到0-1范围
        let normalizedValue;
        if (grayValue <= windowMin) {
          normalizedValue = 0;
        } else if (grayValue >= windowMax) {
          normalizedValue = 1;
        } else {
          normalizedValue = (grayValue - windowMin) / windowWidth;
        }
        
        // 应用伪彩色映射
        const color = applyColorMap(normalizedValue, data.colorMap || 'jet');
        
        // 设置伪彩色值
        pixelData[i] = color.r;         // Red
        pixelData[i + 1] = color.g;     // Green
        pixelData[i + 2] = color.b;     // Blue
        // Alpha保持不变
      }
      
      // 将处理后的数据写回临时canvas
      tempCtx.putImageData(imageData, 0, 0);
      
      // 应用视口变换并绘制到主canvas
      ctx.save();
      
      // 配置主canvas的图像平滑
      configureCanvasSmoothing(ctx);
      
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.scale(viewport.scale, viewport.scale);
      ctx.translate(viewport.translation.x, viewport.translation.y);
      
      ctx.drawImage(tempCanvas, -img.width / 2, -img.height / 2);
      
      ctx.restore();
      
      // 绘制动脉输入点标记
      drawArterialInputPoint(ctx, img);
      
      console.log('Processed image drawn with pseudocolor and window/level:', windowCenter, windowWidth);
    } catch (error) {
      console.error('Error drawing processed image with pseudocolor:', error);
      // 降级到普通绘制
      drawImageWithViewport(ctx, img);
    }
  };

  const applyColorMap = (value, colorMapType) => {
    // 确保值在 0-1 范围内
    const normalized = Math.max(0, Math.min(1, value));
    
    switch (colorMapType) {
      case 'jet':
        // Jet transparent配色方案：透明 -> 深蓝 -> 青色 -> 绿色 -> 黄色 -> 红色
        // 当值为0时，返回黑色（透明效果）
        if (normalized === 0) {
          return { r: 0, g: 0, b: 0 };
        }
        
        if (normalized < 0.125) {
          // 深蓝色
          const t = normalized / 0.125;
          return { r: 0, g: 0, b: Math.round(128 + 127 * t) };
        } else if (normalized < 0.375) {
          // 深蓝到青色
          const t = (normalized - 0.125) / 0.25;
          return { r: 0, g: Math.round(255 * t), b: 255 };
        } else if (normalized < 0.625) {
          // 青色到绿色
          const t = (normalized - 0.375) / 0.25;
          return { r: 0, g: 255, b: Math.round(255 * (1 - t)) };
        } else if (normalized < 0.875) {
          // 绿色到黄色
          const t = (normalized - 0.625) / 0.25;
          return { r: Math.round(255 * t), g: 255, b: 0 };
        } else {
          // 黄色到红色
          const t = (normalized - 0.875) / 0.125;
          return { r: 255, g: Math.round(255 * (1 - t)), b: 0 };
        }
      
      case 'hot':
        if (normalized < 0.33) {
          const t = normalized * 3;
          return { r: Math.round(255 * t), g: 0, b: 0 };
        } else if (normalized < 0.67) {
          const t = (normalized - 0.33) * 3;
          return { r: 255, g: Math.round(255 * t), b: 0 };
        } else {
          const t = (normalized - 0.67) * 3;
          return { r: 255, g: 255, b: Math.round(255 * t) };
        }
      
      case 'cool':
        return { 
          r: Math.round(255 * normalized), 
          g: Math.round(255 * (1 - normalized)), 
          b: 255 
        };
      
      case 'rainbow':
        const h = normalized * 300; // 0-300度，红到紫
        const s = 1;
        const v = 1;
        
        // HSV to RGB 转换
        const c = v * s;
        const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
        const m = v - c;
        
        let r, g, b;
        if (h < 60) {
          r = c; g = x; b = 0;
        } else if (h < 120) {
          r = x; g = c; b = 0;
        } else if (h < 180) {
          r = 0; g = c; b = x;
        } else if (h < 240) {
          r = 0; g = x; b = c;
        } else if (h < 300) {
          r = x; g = 0; b = c;
        } else {
          r = c; g = 0; b = x;
        }
        
        return {
          r: Math.round((r + m) * 255),
          g: Math.round((g + m) * 255),
          b: Math.round((b + m) * 255)
        };
      
      case 'viridis':
        // Viridis 颜色映射的近似实现
        if (normalized < 0.25) {
          const t = normalized * 4;
          return { 
            r: Math.round(68 * (1-t) + 59 * t), 
            g: Math.round(1 * (1-t) + 82 * t), 
            b: Math.round(84 * (1-t) + 139 * t) 
          };
        } else if (normalized < 0.5) {
          const t = (normalized - 0.25) * 4;
          return { 
            r: Math.round(59 * (1-t) + 33 * t), 
            g: Math.round(82 * (1-t) + 144 * t), 
            b: Math.round(139 * (1-t) + 140 * t) 
          };
        } else if (normalized < 0.75) {
          const t = (normalized - 0.5) * 4;
          return { 
            r: Math.round(33 * (1-t) + 94 * t), 
            g: Math.round(144 * (1-t) + 201 * t), 
            b: Math.round(140 * (1-t) + 98 * t) 
          };
        } else {
          const t = (normalized - 0.75) * 4;
          return { 
            r: Math.round(94 * (1-t) + 253 * t), 
            g: Math.round(201 * (1-t) + 231 * t), 
            b: Math.round(98 * (1-t) + 37 * t) 
          };
        }
      
      case 'gray':
      default:
        // 灰度映射
        const gray = Math.round(normalized * 255);
        return { r: gray, g: gray, b: gray };
    }
  };

  const resetViewport = () => {
    const img = imageRef.current;
    if (img) {
      const initialScale = calculateFitScale(img);
      updateViewportSafely({
        scale: initialScale,
        translation: { x: 0, y: 0 },
        windowWidth: 256,
        windowCenter: 128
      });
    } else {
      updateViewportSafely({
        scale: 1,
        translation: { x: 0, y: 0 },
        windowWidth: 256,
        windowCenter: 128
      });
    }
  };

  // 当工具切换为重置时执行重置
  useEffect(() => {
    if (currentTool === 'reset') {
      resetViewport();
    }
  }, [currentTool]);

  // 获取指定坐标的像素值 - 使用useCallback优化
  const getPixelValueAt = useCallback((canvasX, canvasY) => {
    const canvas = canvasRef.current;
    const img = imageRef.current;
    if (!canvas || !img || !imageLoaded) return null;

    try {
      // 将画布坐标转换为图像坐标
      const rect = canvas.getBoundingClientRect();
      const scaleX = canvas.width / rect.width;
      const scaleY = canvas.height / rect.height;
      
      const actualCanvasX = canvasX * scaleX;
      const actualCanvasY = canvasY * scaleY;
      
      // 考虑视图变换
      const centerX = canvas.width / 2;
      const centerY = canvas.height / 2;
      
      const imageX = Math.round((actualCanvasX - centerX) / viewport.scale - viewport.translation.x + img.width / 2);
      const imageY = Math.round((actualCanvasY - centerY) / viewport.scale - viewport.translation.y + img.height / 2);
      
      // 检查坐标是否在图像范围内
      if (imageX < 0 || imageX >= img.width || imageY < 0 || imageY >= img.height) {
        return null;
      }

      // 对于处理后的图像，获取真实参数值
      if (type === 'processed' && data && data.originalData) {
        const pixelIndex = imageY * img.width + imageX;
        const realValue = data.originalData[pixelIndex];
        
        // 确定单位和精度
        let unit = '';
        let precision = 2;
        let displayValue = realValue;
        
        if (viewId === 'ttp') {
          unit = data.physicalUnit || 's';
          precision = 3;
        } else if (viewId === 'mtt') {
          unit = data.physicalUnit || 's';
          precision = 3;
        } else if (viewId === 'auc') {
          unit = data.physicalUnit || '强度·s';
          precision = 3;
        } else if (viewId === 'ph') {
          unit = data.physicalUnit || '强度';
          precision = 1;
        } else if (viewId === 'cbf') {
          unit = data.physicalUnit || 'ml/100g/min';
          precision = 2;
        } else if (viewId === 'cbv') {
          unit = data.physicalUnit || 'ml/100g';
          precision = 2;
        }
        
        return {
          x: imageX,
          y: imageY,
          realValue: parseFloat(displayValue.toFixed(precision)),
          unit: unit,
          grayValue: null, // 对于参数图，灰度值不重要
          rgbValue: null,
          canvasX: Math.round(actualCanvasX),
          canvasY: Math.round(actualCanvasY),
          isParameterImage: true
        };
      }

      // 对于DICOM图像，从canvas获取像素数据
      const ctx = canvas.getContext('2d');
      const imageData = ctx.getImageData(actualCanvasX, actualCanvasY, 1, 1);
      const pixelData = imageData.data;
      
      // 计算灰度值 (如果是RGB则转换为灰度)
      const grayValue = Math.round(0.299 * pixelData[0] + 0.587 * pixelData[1] + 0.114 * pixelData[2]);
      
      return {
        x: imageX,
        y: imageY,
        grayValue: grayValue,
        rgbValue: `R:${pixelData[0]} G:${pixelData[1]} B:${pixelData[2]}`,
        canvasX: Math.round(actualCanvasX),
        canvasY: Math.round(actualCanvasY),
        isParameterImage: false
      };
    } catch (error) {
      console.warn('获取像素值失败:', error);
      return null;
    }
  }, [imageLoaded, viewport.scale, viewport.translation, type, data, viewId]);

  const getCursorStyle = () => {
    if (isDragging) {
      return 'grabbing';
    }
    
    switch (currentTool) {
      case 'pan':
        return 'grab';
      case 'zoom':
        return 'zoom-in';
      case 'windowing':
        return 'crosshair';
      case 'pick':
        return 'crosshair';
      default:
        return 'default';
    }
  };

  // 设置事件监听器（优化版本，减少闪烁）
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    let animationFrameId = null;
    let pendingUpdate = false;

    const scheduleUpdate = (updateFn) => {
      if (!pendingUpdate) {
        pendingUpdate = true;
        animationFrameId = requestAnimationFrame(() => {
          updateFn();
          pendingUpdate = false;
        });
      }
    };

    const handleWheel = (event) => {
      event.preventDefault();
      if (currentTool === 'zoom' || event.ctrlKey) {
        const scaleFactor = event.deltaY > 0 ? 0.9 : 1.1;
        scheduleUpdate(() => {
          setViewport(prev => ({
            ...prev,
            scale: Math.max(0.1, Math.min(10, prev.scale * scaleFactor))
          }));
        });
      }
    };

    // 处理动脉输入点点击
    const handleArterialInputClick = (event) => {
      console.log('handleArterialInputClick 开始执行');
      console.log('imageRef.current:', !!imageRef.current);
      console.log('canvasRef.current:', !!canvasRef.current);
      
      if (!imageRef.current) {
        console.log('imageRef.current 为空，退出');
        return;
      }

      const canvas = canvasRef.current;
      const rect = canvas.getBoundingClientRect();
      
      // 获取原始鼠标坐标
      const mouseX = event.clientX - rect.left;
      const mouseY = event.clientY - rect.top;
      
      // 计算canvas实际分辨率和显示尺寸的缩放比例
      const scaleX = canvas.width / rect.width;
      const scaleY = canvas.height / rect.height;
      
      // 转换为canvas实际坐标
      const canvasX = mouseX * scaleX;
      const canvasY = mouseY * scaleY;

      console.log('鼠标位置:', { mouseX, mouseY });
      console.log('canvas缩放比例:', { scaleX, scaleY });
      console.log('实际canvas坐标:', { canvasX, canvasY });
      console.log('canvas尺寸:', { 
        displayWidth: rect.width, 
        displayHeight: rect.height,
        actualWidth: canvas.width, 
        actualHeight: canvas.height 
      });
      console.log('viewport:', viewport);

      // 转换为图像坐标
      const imageCoords = screenToImageCoords(canvasX, canvasY);
      console.log('转换后的图像坐标:', imageCoords);
      
      if (imageCoords) {
        console.log('动脉输入点标记:', imageCoords);
        console.log('准备调用 onArterialInputPointChange');
        onArterialInputPointChange && onArterialInputPointChange(imageCoords);
        console.log('onArterialInputPointChange 调用完成');
      } else {
        console.log('图像坐标转换失败，imageCoords 为 null');
      }
    };

    // 屏幕坐标转换为图像坐标
    const screenToImageCoords = (screenX, screenY) => {
      console.log('screenToImageCoords 开始执行:', { screenX, screenY });
      
      if (!imageRef.current) {
        console.log('imageRef.current 为空，返回 null');
        return null;
      }

      const canvas = canvasRef.current;
      const img = imageRef.current;
      const { scale, translation } = viewport;

      console.log('图像信息:', { width: img.width, height: img.height });
      console.log('viewport:', { scale, translation });

      // 计算图像在canvas中的显示位置和尺寸
      const displayWidth = img.width * scale;
      const displayHeight = img.height * scale;
      const displayX = (canvas.width - displayWidth) / 2 + translation.x;
      const displayY = (canvas.height - displayHeight) / 2 + translation.y;

      console.log('显示信息:', { displayWidth, displayHeight, displayX, displayY });

      // 检查点击是否在图像区域内
      if (screenX < displayX || screenX > displayX + displayWidth || 
          screenY < displayY || screenY > displayY + displayHeight) {
        console.log('点击位置超出图像区域');
        return null;
      }

      // 转换为图像坐标
      const imageX = ((screenX - displayX) / displayWidth) * img.width;
      const imageY = ((screenY - displayY) / displayHeight) * img.height;

      const result = {
        x: Math.max(0, Math.min(img.width - 1, Math.round(imageX))),
        y: Math.max(0, Math.min(img.height - 1, Math.round(imageY)))
      };

      console.log('最终图像坐标:', result);
      return result;
    };

    const handleMouseDown = (event) => {
      // 动脉输入点标记功能
      if (processingMethod === 'maximum_slope' && currentTool === 'arterial_input') {
        console.log('动脉输入点点击检测:', { processingMethod, currentTool });
        handleArterialInputClick(event);
        return;
      }

      // 窗宽窗位调整对DICOM图像和处理结果都有效
      if (currentTool === 'pan' || currentTool === 'windowing') {
        setIsDragging(true);
        setLastMousePos({ x: event.clientX, y: event.clientY });
      }
    };

    const handleMouseMove = (event) => {
      if (isDragging) {
        const deltaX = event.clientX - lastMousePos.x;
        const deltaY = event.clientY - lastMousePos.y;
        
        scheduleUpdate(() => {
          if (currentTool === 'pan') {
            // 平移功能
            setViewport(prev => ({
              ...prev,
              translation: {
                x: prev.translation.x + deltaX / prev.scale,
                y: prev.translation.y + deltaY / prev.scale
              }
            }));
          } else if (currentTool === 'windowing') {
            // 窗宽窗位调整 - 对DICOM和处理结果都有效
            setViewport(prev => ({
              ...prev,
              windowWidth: Math.max(1, prev.windowWidth + deltaX * 2),
              windowCenter: Math.max(0, Math.min(255, prev.windowCenter + deltaY))
            }));
          }
        });
        
        setLastMousePos({ x: event.clientX, y: event.clientY });
      } else if (currentTool === 'pick' && imageLoaded) {
        // 灰度值拾取模式 - 鼠标悬停时获取像素信息
        const rect = container.getBoundingClientRect();
        const canvasX = event.clientX - rect.left;
        const canvasY = event.clientY - rect.top;
        
        const pixelData = getPixelValueAt(canvasX, canvasY);
        setPixelInfo(pixelData);
        setShowPixelInfo(pixelData !== null);
      }
    };

    const handleMouseUp = () => {
      setIsDragging(false);
    };

    const handleMouseLeave = () => {
      setIsDragging(false);
      // 当鼠标离开时隐藏像素信息
      if (currentTool === 'pick') {
        setShowPixelInfo(false);
        setPixelInfo(null);
      }
    };

    const handleClick = (event) => {
      if (currentTool === 'zoom' && !isDragging) {
        // 左键点击缩放
        const scaleFactor = event.shiftKey ? 0.8 : 1.25; // Shift+点击缩小
        scheduleUpdate(() => {
          setViewport(prev => ({
            ...prev,
            scale: Math.max(0.1, Math.min(10, prev.scale * scaleFactor))
          }));
        });
      }
    };

    // 添加事件监听器，明确设置passive: false以允许preventDefault
    container.addEventListener('wheel', handleWheel, { passive: false });
    container.addEventListener('mousedown', handleMouseDown);
    container.addEventListener('mousemove', handleMouseMove);
    container.addEventListener('mouseup', handleMouseUp);
    container.addEventListener('mouseleave', handleMouseLeave);
    container.addEventListener('click', handleClick);

    // 清理函数
    return () => {
      if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
      }
      container.removeEventListener('wheel', handleWheel);
      container.removeEventListener('mousedown', handleMouseDown);
      container.removeEventListener('mousemove', handleMouseMove);
      container.removeEventListener('mouseup', handleMouseUp);
      container.removeEventListener('mouseleave', handleMouseLeave);
      container.removeEventListener('click', handleClick);
    };
  }, [currentTool, isDragging, lastMousePos, imageLoaded, viewport.scale, getPixelValueAt]);

  return (
    <div className="image-viewer">
      <div className="viewer-header">
        <h3>{title}</h3>
        <div className="header-buttons">
          {showTdcButton && (
            <button
              className={`tdc-header-button ${tdcMode ? 'active' : ''}`}
              onClick={onToggleTdc}
              title={tdcMode ? '退出TDC分析模式' : '进入TDC分析模式'}
            >
              <span className="tdc-icon">📊</span>
              <span className="tdc-text">标记TDC</span>
              {tdcMode && <span className="tdc-status">分析中</span>}
            </button>
          )}
          {showVesselButton && (
            <button
              className={`vessel-header-button ${vesselMode ? 'active' : ''}`}
              onClick={onToggleVessel}
              title={vesselMode ? '退出血管提取模式' : '进入血管提取模式'}
            >
              <span className="vessel-icon">🩸</span>
              <span className="vessel-text">血管提取</span>
              {vesselMode && <span className="vessel-status">提取中</span>}
            </button>
          )}
        </div>
      </div>
      
      <div className="viewer-content">
        <div 
          ref={containerRef}
          className="simple-viewer-container"
          style={{ cursor: getCursorStyle() }}
        >
          <canvas 
            ref={canvasRef}
            style={{ 
              width: '100%', 
              height: '100%',
              display: 'block'
            }}
          />
          
          {errorMessage && (
            <div className="error-overlay">
              <div className="error-message">
                ⚠️ {errorMessage}
              </div>
            </div>
          )}
        </div>
        
        {type === 'processed' && data && (
          <div className="colorbar">
            <div className={`colorbar-gradient ${data.colorMap === 'hot' ? 'hot' : ''}`}></div>
            <div className="colorbar-labels">
              <span>{data.max?.toFixed(2) || '1.0'}</span>
              <span>{((data.max + data.min) / 2)?.toFixed(2) || '0.5'}</span>
              <span>{data.min?.toFixed(2) || '0.0'}</span>
            </div>
          </div>
        )}
      </div>
      
      {type === 'dicom' && data?.images && data.images.length > 1 && (
        <div className="frame-slider-bottom">
          <div className="slider-container">
            <div className="slider-track">
              <input
                type="range"
                min="0"
                max={data.images.length - 1}
                value={currentImageIndex}
                onChange={(e) => setCurrentImageIndex(parseInt(e.target.value))}
                className="frame-slider-main"
              />
              <div className="slider-progress" 
                   style={{ width: `${(currentImageIndex / (data.images.length - 1)) * 100}%` }}
              />
            </div>
            <span className="frame-counter">
              {currentImageIndex + 1} / {data.images.length}
            </span>
          </div>
        </div>
      )}
      
      <div className="viewer-info">
        <div className="viewport-info">
          <span>缩放: {viewport.scale.toFixed(2)}x</span>
          <span>窗宽: {Math.round(viewport.windowWidth)}</span>
          <span>窗位: {Math.round(viewport.windowCenter)}</span>
          <span>插值: {enableInterpolation ? '开启' : '关闭'}</span>
          {/* 像素信息显示 */}
          {showPixelInfo && pixelInfo && (
            <span className="pixel-info">
              坐标: ({pixelInfo.x}, {pixelInfo.y}) | 
              {pixelInfo.isParameterImage ? 
                `参数值: ${pixelInfo.realValue} ${pixelInfo.unit}` : 
                `灰度: ${pixelInfo.grayValue}`
              }
            </span>
          )}
        </div>
        <div className="image-info">
          <span>当前工具: {currentTool === 'pick' ? '灰度拾取' : currentTool}</span>
          <span>状态: {imageLoaded ? '已加载' : '加载中'}</span>
          <span>类型: {type === 'dicom' ? 'DICOM' : '处理结果'}</span>
          {/* 显示文件名信息 */}
          {type === 'dicom' && data && (
            <>
              {data.metadata?.fileCount > 1 ? (
                // 多文件场景：显示当前帧的文件名
                data.images && data.images[currentImageIndex] && (
                  <span>文件: {data.images[currentImageIndex].fileName || '未知'}</span>
                )
              ) : (
                // 单文件（多帧）场景：显示源文件名
                data.metadata?.originalFileName && (
                  <span>文件: {data.metadata.originalFileName}</span>
                )
              )}
              {data.metadata?.fileCount && (
                <span>总文件: {data.metadata.fileCount}个</span>
              )}
            </>
          )}
          <span>容器: {containerSize.width}×{containerSize.height}</span>
          {/* 在拾取模式下显示操作提示 */}
          {currentTool === 'pick' && (
            <span className="pick-tip">💡 移动鼠标查看像素值</span>
          )}
        </div>
      </div>
    </div>
  );
};

export default SimpleImageViewer; 